package tech.gismap.admin.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tech.gismap.admin.domain.OaMenu;
import tech.gismap.admin.web.bo.OaMenuBo;
import tech.gismap.admin.web.vo.OaMenuTreeVo;
import tech.gismap.admin.web.vo.OaMenuVo;
import tech.gismap.admin.mapper.OaMenuMapper;
import tech.gismap.common.core.utils.MapstructUtils;
import tech.gismap.common.mybatis.core.page.PageQuery;
import tech.gismap.common.mybatis.core.page.TableDataInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 菜单
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OaMenuService {

    private final OaMenuMapper baseMapper;

    /**
     * 获取分页页面
     * @param bo 查询参数
     * @param pageQuery 分页参数
     * @return 分页列表
     */
    public TableDataInfo<OaMenuVo> selectPageList(OaMenuBo bo, PageQuery pageQuery) {
        Page<OaMenuVo> page = baseMapper.selectVoPage(pageQuery.build(), this.buildQueryWrapper(bo));
        return TableDataInfo.build(page);
    }

    /**
     * 构建查询条件
     * @param bo 菜单查询对象
     * @return 菜单查询对象
     */
    private Wrapper<OaMenu> buildQueryWrapper(OaMenuBo bo) {
        LambdaQueryWrapper<OaMenu> wrapper = Wrappers.lambdaQuery();
        wrapper.orderByDesc(OaMenu::getUpdateTime);
        return wrapper;
    }

    /**
     * 获得树列表
     * @param id 父级标识码
     * @return 结果
     */
    public OaMenuTreeVo selectListTree() {
        OaMenuTreeVo result = MapstructUtils.convert(baseMapper.selectById(1L), OaMenuTreeVo.class);
        if (result != null) {
            result.setChildren(addChildren(String.valueOf(result.getId())));
        }
        return result;
    }

    /**
     * 添加子集菜单
     * @param parentId 上级标识码
     * @return 菜单列表
     */
    private List<OaMenuTreeVo> addChildren(String parentId) {
        List<OaMenuTreeVo> result = new ArrayList<>();
        LambdaQueryWrapper<OaMenu> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(OaMenu::getParentId, parentId);
        List<OaMenu> list = baseMapper.selectList(wrapper);
        if (!list.isEmpty()) {
            result.addAll(Objects.requireNonNull(MapstructUtils.convert(list, OaMenuTreeVo.class)));
            for (OaMenuTreeVo menu : result) {
                menu.setChildren(addChildren(String.valueOf(menu.getId())));
            }
        }
        return result;
    }
}
